<template>
    <div class="prize-table-main">
        <el-table :data="formParams.reward_list" class-name="reward-list">
            <template v-for="(item, index) in tableField" :key="index">
                <template v-if="item.type == 1">
                    <el-table-column :label="item.label" min-width="146">
                        <template #header>
                            <formItemLabel label="奖品等级" content="完成任务的奖品等级，最多5级" />
                        </template>
                        <template #default="{ $index }">
                            {{ rewardLevenMap[$index] }}
                        </template>
                    </el-table-column>
                </template>
                <template v-if="item.type == 2">
                    <el-table-column prop="reward_title" :label="item.label" min-width="122" show-overflow-tooltip />
                </template>
                <template v-if="item.type == 3">
                    <el-table-column prop="reward_image" :label="item.label" min-width="78" align="center">
                        <template #default="{ row }: IRewardColumn">
                            <el-image class="reward-image" :src="row.reward_image"></el-image>
                        </template>
                    </el-table-column>
                </template>
                <template v-if="item.type == 4">
                    <el-table-column prop="reward_type" :label="item.label" min-width="122">
                        <template #default="{ row }: IRewardColumn">
                            {{ renderRewardTypeName(row.reward_type) }}
                        </template>
                    </el-table-column>
                </template>
                <template v-if="item.type == 5">
                    <el-table-column prop="reward_stock" :label="item.label" min-width="122" />
                </template>
                <template v-if="item.type == 6">
                    <el-table-column prop="help_num" :label="item.label" min-width="132">
                        <template #header>
                            <formItemLabel :label="item.label" content="用户领取奖品所需要的助力人数" />
                        </template>
                    </el-table-column>
                </template>
                <template v-if="item.type == 7">
                    <el-table-column prop="exchange_usage_type" :label="item.label" min-width="122">
                        <template #default="{ row }: IRewardColumn">
                            {{ renderExchangeUsageTypeName(row.exchange_usage_type, row) }}
                        </template>
                    </el-table-column>
                </template>
                <template v-if="item.type == 8">
                    <el-table-column prop="name" :label="item.label" min-width="130" fixed="right">
                        <template #default="{ row, $index }: IRewardColumn">
                            <el-button v-if="isRenderType('View')" type="primary" link @click="viewReward(row, $index)">
                                查看
                            </el-button>
                            <el-button v-if="isRenderType('Edit')" type="primary" link @click="editReward(row, $index)">
                                编辑
                            </el-button>
                            <el-button
                                v-if="isRenderType('Del', $index, row)"
                                type="primary"
                                link
                                @click="delReward($index)">
                                删除
                            </el-button>
                        </template>
                    </el-table-column>
                </template>
            </template>
        </el-table>
        <el-tooltip
            :visible="rewardTootipVisible"
            :content="`已达添加上限${MAX_REWARD_LENGTH}个`"
            placement="top-start">
            <div
                class="button-tooltip-trigger"
                @mouseenter="handleRewardMouseenter"
                @mouseleave="handleRewardMouseleave">
                <el-button
                    type="primary"
                    plain
                    :disabled="pageType.look || formParams.reward_list.length >= MAX_REWARD_LENGTH"
                    @click="openAddReward">
                    <el-icon><Plus /></el-icon>
                    <span>添加奖品</span>
                </el-button>
            </div>
        </el-tooltip>
    </div>
</template>
<script setup lang="ts">
import formItemLabel from './form-item-label/form-item-label.vue';
import { IRewardRow, IRewardColumn, IPageType } from '../utils/interface';
import { formParams, setPrizeFormParams, initFormParams } from '../utils/paramsManager';
import fieldInfo from '../utils/modules';
import { useRoute } from 'vue-router';
import { ref, reactive, onUnmounted } from 'vue';

const route = useRoute();

const emit = defineEmits(['openAddReward', 'editReward', 'delReward', 'viewReward']);

const props = defineProps({
    type: {
        type: String,
        default: 'FISSION_DRAINAGE'
    }
});

const tableField = fieldInfo[props.type].table || [];

const pageType = reactive<IPageType>({
    look: route.query.type === 'look',
    edit: route.query.type === 'edit',
    new: route.query.type === 'new',
    copy: route.query.type === 'copy'
});

// 渲染12345级奖品文字
const rewardLevenMap = ['一级奖品', '二级奖品', '三级奖品', '四级奖品', '五级奖品'];

/**
 * 根据奖品类型渲染对应的中文
 * @param rewardType 奖品类型
 * @returns {String} '实物奖品'|'红包奖品'
 */
const renderRewardTypeName = function (rewardType: number) {
    const typeMap = {
        1: '实物奖品',
        2: '红包奖品'
    };
    return typeMap[rewardType] ?? '-';
};

/**
 * 根据兑换类型渲染对应的中文
 * @param exchangeUsageType 兑换类型
 * @returns {String} '兑换码'|'线下邮寄'
 */
const renderExchangeUsageTypeName = function (exchangeUsageType: number, rewardRow: IRewardRow) {
    if (rewardRow.reward_type === 2) {
        return '-';
    }
    const typeMap = {
        1: '兑换码',
        2: '线下邮寄'
    };
    return typeMap[exchangeUsageType] ?? '-';
};

/* -----------------------------创建控制tootip显示的工厂-start---------------------------- */
/**
 * @description 创建控制tootip显示的工厂
 * @param maxlength 长度
 * @param list 数组
 * @returns {[tootipVisbleRef, mouseenterFn, mouseleaveFn]}
 */
const tootipFactory = (maxlength: number, listKey: string) => {
    const tootipVisible = ref<boolean>(false);
    /**
     * @description 鼠标移入展示tootip，根据当前是否选中的条数超过最大条
     */
    const mouseenter = () => {
        tootipVisible.value = formParams[listKey].length >= maxlength;
    };
    /**
     * @description 鼠标移入隐藏tootip
     */
    const mouseleave = () => {
        tootipVisible.value = false;
    };

    const ret: Array<any> = [tootipVisible, mouseenter, mouseleave];
    return ret;
};
/* -----------------------------创建控制tootip显示的工厂-end---------------------------- */

// 奖品tootip
/**
 * @description 最大奖品数量
 */
const MAX_REWARD_LENGTH = 5;

const [rewardTootipVisible, handleRewardMouseenter, handleRewardMouseleave] = tootipFactory(
    MAX_REWARD_LENGTH,
    'reward_list'
);

/** 按钮类型 */
type buttonType = 'View' | 'Edit' | 'Del';
/**
 * 是否渲染当前按钮
 * @param buttonType 按钮类型
 * @param index 当前索引
 * @param row 当前奖品
 * @returns {Boolean}
 */
const isRenderType = (buttonType: buttonType, index?: number, row?: IRewardRow) => {
    switch (buttonType) {
        case 'View':
            return pageType.look;
        case 'Edit':
            return !pageType.look;
        case 'Del': // 不是第一条，并且是新增的奖品可以删除。并且不是查看的情况下
            return (
                typeof index !== 'undefined' && // 这一句是为了ts不报错
                index > 0 &&
                Boolean(row?.is_add_reward) && // 加boolean只是为了ts不报错
                !pageType?.look
            );
        default:
            return true;
    }
};

/**
 * 编辑奖品列表的数据
 * @param row 奖品数据信息
 */
const editReward = (row: IRewardRow, index: number) => {
    emit('editReward', row, index);
};

/**
 * 查看奖品数据，和新增弹窗一样
 * @param row 奖品数据信息
 */
const viewReward = (row: IRewardRow, index: number) => {
    emit('viewReward', row, index);
};

/**
 * 删除奖品列表的数据
 * @param row 奖品数据信息
 */
const delReward = (index: number) => {
    formParams.reward_list.splice(index, 1);
    emit('delReward', index);
};

/**
 * 打开添加奖品弹窗
 */
const openAddReward = () => {
    emit('openAddReward');
};

const setFormParams = (data: any) => {
    setPrizeFormParams(data);
};

onUnmounted(() => {
    // 组件销毁后初始化params
    initFormParams();
});

defineExpose({
    setFormParams
});
</script>
<style lang="scss" scoped>
.prize-table-main {
    :deep(.reward-list) {
        border: 0 none;

        .el-button.is-link {
            min-width: auto !important;
            margin: 0 16px 0 0 !important;
            padding: 0 !important;

            &:focus {
                color: #ff6b00;
                outline: none;
            }
        }

        .el-table__inner-wrapper .el-table__header-wrapper .el-table__header thead tr th {
            padding: 14px 0;
            background-color: #f9f9f9;
        }
    }

    // 有禁用的tootip按钮的外包装div
    .button-tooltip-trigger {
        display: inline-block;
        margin-top: 15px;
        vertical-align: middle;
    }

    .reward-image {
        width: 28px;
        height: 28px;
    }

    .form-item-label {
        display: flex;
        align-items: center;

        :deep(.el-icon) {
            margin-left: 4px;
        }
    }
}

:deep(.el-button.el-button--primary.is-plain:not(.is-disabled)) {
    --el-button-bg-color: #fff;
    --el-button-border-color: var(--el-color-primary);

    &:hover {
        color: #ff6b00;
        border-color: #ff6b00;
        background-color: #fdefe5;
    }

    &:focus {
        color: #ff6b00;
        background-color: var(--el-button-bg-color);
        border: 1px solid #ffb580;
        outline: none;
    }
}
</style>
